package org.springblade.third.aspect;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springblade.third.dto.ThirdRequest;
import org.springblade.third.entity.InvokeLog;
import org.springblade.third.mapper.InvokeLogMapper;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class ThirdInvokeLogAspect {

    private final InvokeLogMapper invokeLogMapper;

    @Around("execution(* org.springblade.third.service.ThirdInvokeService.invoke(..)) && args(request)")
    public Object aroundInvoke(ProceedingJoinPoint pjp, ThirdRequest request) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            Object resp = pjp.proceed();
            long cost = System.currentTimeMillis()-start;
            log.info("third-invoke success channel={} product={} costMs={} bizId={}", request.getChannelCode(), request.getProductCode(), cost, request.getBizId());
            saveLog(request, cost, 1, "OK");
            return resp;
        } catch (Throwable ex) {
            long cost = System.currentTimeMillis()-start;
            log.warn("third-invoke failed channel={} product={} costMs={} bizId={} msg={}", request.getChannelCode(), request.getProductCode(), cost, request.getBizId(), ex.getMessage());
            saveLog(request, cost, 0, ex.getMessage());
            throw ex;
        }
    }

    private void saveLog(ThirdRequest req, long cost, int success, String msg) {
        try {
            InvokeLog logEntity = new InvokeLog();
            logEntity.setChannelCode(req.getChannelCode());
            logEntity.setProductCode(req.getProductCode());
            logEntity.setBizId(req.getBizId());
            logEntity.setCostMs(cost);
            logEntity.setSuccess(success);
            logEntity.setMessage(msg);
            invokeLogMapper.insert(logEntity);
        } catch (Exception ignore) {
        }
    }
}


